package com.tools;

import com.baidu.aip.ocr.AipOcr;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Scanner;

public class BaiduOCR {
    public static final String APP_ID = "10654272";
    public static final String API_KEY = "fzAlHIa4f1C0xs388bfIMotb";
    public static final String SECRET_KEY = "SiOZePWHVRaRkhrVTmDQA2o8GAxHoCjb";

    public static void main(String[] args) throws IOException, InterruptedException {
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        Scanner sca=new Scanner(System.in);
        System.out.println("回车开一局");
        String path = new BaiduOCR().getClass().getClassLoader().getResource("").getPath()+"test.png";
        File f=new File(path);
        if (!f.exists()) {
            docommond("screencapture -R40,90,336,330 "+ path);
        }
        client.basicGeneral(path, new HashMap<String, String>());
        while(sca.nextLine()!=null){
            System.out.println(System.currentTimeMillis());
            docommond("screencapture -R40,90,336,330 "+ path);
            // 初始化一个AipOcr
            // 调用接口
            BinaryTest.smallit(path);
            System.out.println(System.currentTimeMillis());
            JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
            //
// System.out.println(res.toString(2));
            String allWords="";
            JSONArray jarr=res.getJSONArray("words_result");
//            boolean haswen=false;
            for(int i=0;i<jarr.length();i++){
                JSONObject obj=jarr.getJSONObject(i);
                String word=obj.getString("words").trim();
                if (i==0) {
                    word=word.substring(1);
                }
                allWords+=word;
                if (word.contains("?")) {
//                    haswen=true;
                    allWords+=" 答案";
                    break;
                }
            }
            allWords=allWords.replace("\\u201c","").replace("\\u201d","");
            System.out.println(System.currentTimeMillis());
            docommond("open https://www.baidu.com/s?wd="+ URLEncoder.encode(allWords,"UTF-8"));
//        BaiTest.simple("https://www.baidu.com/s?wd="+ URLEncoder.encode(allWords,"UTF-8"));
            System.out.println(allWords);
            System.out.println("https://www.baidu.com/s?wd="+ URLEncoder.encode(allWords,"UTF-8"));
            System.out.println(System.currentTimeMillis());
        }

    }

    private static void docommond(String commond) throws InterruptedException, IOException {
        Process proc = Runtime.getRuntime().exec(commond);
        proc.waitFor(); //阻塞，直到上述命令执行完
    }
}
